package ext.tianma.part.processors;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.method.RemoteAccess;
import wt.part.QuantityUnit;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTInvalidParameterException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.workflow.engine.WfEngineHelper;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.part.forms.PartUtil;
import ext.tianma.workflow.workflowCommands;

public class SecondSupplierProcessor extends DefaultObjectFormProcessor implements RemoteAccess, Serializable
{
	private static boolean VERBOSE = false;
    private static String CLASSNAME = SecondSupplierProcessor.class.getName();
    private static final String RESOURCE = "ext.tianma.resource.ResourceRB";
    //物料生效地
  	private static final String PART_NUMBER_EFFECTIVE_SITE = "partNumberEffectiveSite" ;
  	private static final String VIEW_A20 = "A20" ;
  	private static final String VIEW_C06 = "C06" ;
    private static String materialExcelPath = "" ;
	public static WTProperties wtProperties = null ;
    
    static
    {
        try
        {
            WTProperties wtproperties = WTProperties.getLocalProperties();
            VERBOSE = wtproperties.getProperty("ext.tianma.part.verbose", false);
            
            wtProperties = WTProperties.getLocalProperties();
            materialExcelPath = wtProperties.getProperty("ext.tianma.part.materials");
        }
        catch (Throwable throwable)
        {
            throwable.printStackTrace(System.err);
            throw new ExceptionInInitializerError(throwable);
        }
    }
	@Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1) throws WTException {
		FormResult formresult = new FormResult();
		formresult.setStatus(FormProcessingStatus.SUCCESS);
	
		NmOid nmoid = arg0.getActionOid();
		WTPart currentPart = (WTPart) nmoid.getRefObject();		
		String number = currentPart.getNumber();
		System.out.println("Debug  二供物料编码申请流程"+currentPart.getNumber());
		String softType = IBAUtil.getSoftType(currentPart).getLogicalIdentifier();
		softType = softType.substring(softType.indexOf(".")+1);
		Locale locale = SessionHelper.getLocale();
		WTPart newPart  = null;
		try {
			newPart = PartCommands.saveNewPart(currentPart);
		} catch (WTPropertyVetoException e) {
			throw new WTException(e.toString());
		}
		System.out.println("Debug 二供物料编码申请流程"+newPart.getNumber());
		
		/**
		 * @author xuge_ning
		 * @reason处理历史数据问题，进阶时不再使用A20视图,C06视图
		 */
		try {
			Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(newPart, PART_NUMBER_EFFECTIVE_SITE);
			View[] allViews = ViewHelper.service.getAllViews();
			System.out.println("Debug  版本进阶视图allViews：" + allViews.toString());
			if(partNumberEffectiveSite != null){
				String updatePartNumberEffectiveSite = "";
				for (int i = 0; i < partNumberEffectiveSite.size(); i++) {
					Object obj = partNumberEffectiveSite.get(i);
					if( obj != null && obj instanceof String ){
						System.out.println("Debug  版本进阶料号生效地" +  obj.toString());
						if(!VIEW_A20.equals((String)obj) && !VIEW_C06.equals((String)obj)){
							if("".equals(updatePartNumberEffectiveSite)){
								updatePartNumberEffectiveSite = (String) obj;
							} else{
								updatePartNumberEffectiveSite = updatePartNumberEffectiveSite + "," + (String) obj;
							}
						}
						
						System.out.println("Debug  版本进阶料号生效地总汇" +  updatePartNumberEffectiveSite);
					}
				}
				CusIBAUtil.forceSetEnumIBAValue( newPart , PART_NUMBER_EFFECTIVE_SITE , updatePartNumberEffectiveSite );
			}
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		
		Vector usagelinks2 =  CoreUtil.getPartUsageLinks(newPart);                
        for(int c = 0; c < usagelinks2.size(); c++)
        {
            WTPartUsageLink usagelink = (WTPartUsageLink)usagelinks2.elementAt(c);
            PersistenceServerHelper.manager.remove(usagelink); 
        }
       // WfEngineHelper.service.TerminateObjectsRunningWorkflows((LifeCycleManaged)newPart);

        WfEngineHelper.service.terminateObjectsRunningWorkflows(newPart);
        
        try {
			workflowCommands.startRAWTransitFactoryWorkFlow(newPart);
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			throw new WTException(e.toString());
		}
		
		//更新零部件默认单位
        try {
			String value=(String) IBAUtil.getIBAValue( newPart , "partEName");
			String unit=PartUtil.getRawMaterialsUnit(getWorkbook( materialExcelPath ).getSheetAt(1), value);
			changePartUnit( newPart , unit);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
		FeedbackMessage feedbackmessage = new FeedbackMessage(
				FeedbackType.SUCCESS, null, "启动第二供应商流程", null, new String[] {});
		formresult.addFeedbackMessage(feedbackmessage);
		return formresult;
	}
	
	/**
	 * 修改零部件的默认单位
	 * 
	 * @param part
	 * @param unit
	 */
	public static void changePartUnit(WTPart part , String unit){
		if( part == null ){
			System.out.println(">>>>> 设置单位, part == null");
			return ;
		}
		
		if( unit == null || unit.equals("")){
			System.out.println(">>>>> 设置单位, unit == null");
			return ;
		}
		
		QuantityUnit quantityUnit = QuantityUnit.toQuantityUnit(unit);
		
		if( quantityUnit != null ) {			
			WTPartMaster partMaster = (WTPartMaster)part.getMaster() ;
			
			try{
				System.out.println(">>>>> 开始设置单位！");
				
				//更新单位
				partMaster.setDefaultUnit( quantityUnit );
				partMaster = (WTPartMaster)PersistenceHelper.manager.save( partMaster ); 
				
				System.out.println(">>>>> 设置单位成功！");
			} catch (WTInvalidParameterException e) {
				e.printStackTrace();
			} catch (WTPropertyVetoException e) {
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
		}else{
			System.out.println(">>>>> 设置单位, 单位为空." + unit + " 不能转换为单位.");
		}
	}

	public static Workbook getWorkbook(String path){
		Workbook  workbook = null;
		
		InputStream in = null;
		
		try {
			in = new FileInputStream(path);
			
			workbook = WorkbookFactory.create(in);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} finally{
			closeStream(in);
			
			if( workbook == null ){
				System.out.println(">>>>> Can't get Excel Workbook by excel file path : " + path ) ;
			}
		}
		
		return workbook ;
	}
	
	public static void closeStream(InputStream in) {
		if( in != null ){
			try {
				in.close() ;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
